<template>
  <div :id="chartId" style="width: 90%; height: 16rem;margin-left: calc(50% - 7rem)"></div>
</template>

<script setup>
import {defineProps, onBeforeUnmount, onMounted, ref, watchEffect} from 'vue';
import * as echarts from 'echarts/core';
import {GaugeChart} from 'echarts/charts';
import {CanvasRenderer} from 'echarts/renderers';

// 引入生成唯一ID的方法（这里仅作演示，实际上需要选择一种方法）
const generateUniqueId = () => `chart_${Math.floor(Math.random() * Date.now())}`;

echarts.use([GaugeChart, CanvasRenderer]);

const props = defineProps({
  color: {
    type: Array,
    default: () => ['#02d6fc', '#367bec'] // 默认渐变色
  },
  value: {
    type: Number,
    default: 20
  },
  name: {
    type: String,
    default: '知识点掌握'
  }
});

const chartId = ref(generateUniqueId());

let myChart = null;

const initChart = () => {
  const chartDom = document.getElementById(chartId.value);
  myChart = echarts.init(chartDom);
  const gaugeData = [
    {
      value: props.value,
      name: props.name,
      title: {
        fontSize: 14,
        offsetCenter: ['0%', '20%']
      },
      detail: {
        valueAnimation: true,
        fontSize: 20,
        offsetCenter: ['0%', '-10%']
      }
    }
  ];
  const option = {
    series: [
      {
        type: 'gauge',
        startAngle: 90,
        endAngle: -270,
        pointer: {
          show: false
        },
        // 在series配置中
        progress: {
          show: true,
          overlap: false,
          roundCap: true,
          clip: false,
          itemStyle: {
            borderWidth: 0,
            borderColor: '#464646',
            color: new echarts.graphic.LinearGradient(-0.3, -0.3, 1, 1, [
              {offset: 0, color: props.color[0]}, // 起始颜色
              {offset: 1, color: props.color[1]} // 结束颜色
            ])
          }
        },
        axisLine: {
          lineStyle: {
            width: 30
          }
        },
        splitLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          show: false
        },
        data: gaugeData,
        title: {
          fontSize: 8
        },
        detail: {
          fontSize: 8,
          formatter: '{value}%'
        }
      }
    ]
  };

  myChart.setOption(option);
};

onMounted(() => {
  initChart();
});

onBeforeUnmount(() => {
  if (myChart != null) {
    myChart.dispose();
  }
});

// 监听props变化以更新图表
watchEffect(() => {
  if (myChart) {
    initChart();
  }
});
</script>

<style scoped>

</style>
